package graduationorder.graduationorder.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import graduationorder.graduationorder.service.vo.AuthUser;

import java.util.Calendar;
import java.util.Map;

/**
 * @author Mzk
 * @version 1.0
 * @description: jwt
 * @date 2024/8/3 下午 3:28
 */
public class JWTUtils {
    private static String TOKEN = "token!Q@W3e4r";

    public static String getToken(Map<String,String> map){
        JWTCreator.Builder builder = JWT.create();
        map.forEach((k,v)->{
            builder.withClaim(k,v);
        });
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.HOUR,12);
        builder.withExpiresAt(instance.getTime());
        return builder.sign(Algorithm.HMAC256(TOKEN)).toString();
    }
    /**
     * 验证token
     * @param token
     */
    public static void verify(String token){
        JWT.require(Algorithm.HMAC256(TOKEN)).build().verify(token);
    }
    /**
     * 获取token中payload
     * @param  token
     * @return AuthUser
     */
    public static AuthUser getAuthedUser(String token){
        DecodedJWT verify = JWT.require(Algorithm.HMAC256(TOKEN)).build().verify(token);
        Map<String, Claim> claims = verify.getClaims();
        return new AuthUser(
                Integer.parseInt(claims.get("id").asString())
                , claims.get("userName").asString()
                , claims.get("employeeId").asString()
                , claims.get("authName").asString()
                , claims.get("auth").asString()
                , claims.get("contactInfo").asString()
        );
    }
}
